package com.vvlive.caibao.smartcity.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vvlive.caibao.smartcity.adapter.IndexFunctionAdapter;
import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.base.FunctionEditable;
import com.vvlive.caibao.smartcity.bean.IndexFuncationListBean;
import com.vvlive.caibao.smartcity.bean.User;
import com.vvlive.caibao.smartcity.ui.AddActivity;
import com.vvlive.caibao.smartcity.ui.CheckOnActivity;
import com.vvlive.caibao.smartcity.ui.CreateAccountAtivity;
import com.vvlive.caibao.smartcity.ui.FilesInputActivity;
import com.vvlive.caibao.smartcity.ui.SignInActivity;
import com.vvlive.caibao.smartcity.utils.AddFunctionUtils;
import com.vvlive.caibao.smartcity.utils.DialogUtil;
import com.vvlive.caibao.smartcity.utils.FuncationInitUtils;
import com.vvlive.caibao.smartcity.utils.SettingsUtil;
import com.vvlive.caibao.smartcity.view.RoundImageView;

import org.askerov.dynamicgrid.DynamicGridView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by lenovo on 2015/6/26.
 * 首页
 */
public class IndexFragment extends Fragment implements
        AdapterView.OnItemClickListener, FunctionEditable {

    //添加功能页面请求码
    private final static int ADD_ACTIVITY_REQUEST_CODE = 1;
    private DynamicGridView mGridView;
    //需要添加功能的序列
    private IndexFunctionAdapter mIndexFunctionAdapter;
    private TextView title_text;
    //存放对应功能的activity类
    private List<IndexFuncationListBean> mListFuncations = new ArrayList<>();
    private List<IndexFuncationListBean> mAllList = new ArrayList<>();
    //用于存放功能标记
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    private FuncationInitUtils mInfo;
    private String mSign;
    //功能的顺序,用于item的移动
    private String order;
    private String[] odr;

    private LinearLayout mLoginRegister;
    private View mLoginedHeader;
    private Button mLogin;
    private Button mRegister;

    private RoundImageView mLoginAvatar;
    // 显示已经登录的用户名
    private TextView mLoginUser;

    private View mContentView;

    private boolean mHasDeleted = false;

    private Click mClick;
    private ConfirmDialogClick mDialogClick;

    private SettingsUtil mSettings;
    private Map<String, String> mUserInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.index_layout, null);
        //图标
        mGridView = (DynamicGridView) mContentView.findViewById(R.id.index_gridlview);

        mGridView.setOnItemClickListener(this);
        mGridView.setOnDragListener(new DynamicGridView.OnDragListener() {
            @Override
            public void onDragStarted(int position) {
                mHasDeleted = false;
//                mIndexFunctionAdapter.setEditable(true);
            }

            @Override
            public void onDragPositionsChanged(int oldPosition, int newPosition) {
                o = oldPosition;
                n = newPosition;
                moveItem();
            }
        });

        mClick = new Click();
        mDialogClick = new ConfirmDialogClick();
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (SmartCityApp.isLogin) {
                    mGridView.startEditMode(position);
                } else {
                    showLoginFirstDialog();
                }
                return true;
            }
        });
        //获取全部的功能列表
        mInfo = new FuncationInitUtils();
        mAllList = mInfo.addAllFuncation();
        //
        mPreferences = getActivity().getSharedPreferences("funcation", 0);
        //默认的列表
        getInitList();
        //登录 注册
        mLogin = (Button) mContentView.findViewById(R.id.login);
        mLogin.setOnClickListener(mClick);
        mRegister = (Button) mContentView.findViewById(R.id.register);
        mRegister.setOnClickListener(mClick);

        mLoginRegister = (LinearLayout) mContentView.findViewById(R.id.login_register);
        mLoginedHeader = mContentView.findViewById(R.id.logined_header);

        mLoginAvatar = (RoundImageView) mContentView.findViewById(R.id.logined_avatar);
        mLoginAvatar.setOnClickListener(mClick);

        mSettings = new SettingsUtil(getActivity());
        mUserInfo = mSettings.getUserInfo();
        if (!"".equals(mUserInfo.get(SettingsUtil.KEY_USERID))) {
            setLoginState(true);
        } else {
            setLoginState(false);
        }

        return mContentView;
    }

    /**
     *
     */
    private AlertDialog.Builder mBuilder;

    /**
     * 显示首先登录的对话框
     */
    private void showLoginFirstDialog() {
        if (mBuilder == null) {
            mBuilder = new AlertDialog.Builder(getActivity());
        }
        mBuilder.setMessage("请先登录再执行此操作")
                .setNegativeButton("取消", mDialogClick)
                .setPositiveButton("登录", mDialogClick)
                .show();
    }

    private class ConfirmDialogClick implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case DialogInterface.BUTTON_NEGATIVE:
                    dialog.dismiss();
                    break;
                case DialogInterface.BUTTON_POSITIVE:
                    dialog.dismiss();
                    login();
                    break;
            }

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = getIntentInstance(mListFuncations.get(position).getActivity());

        if (SmartCityApp.isLogin) {
            //判断是否是添加
            if (position != mListFuncations.size() - 1) {
                IndexFuncationListBean bean = mListFuncations.get(position);
                if (bean.getActivity() != AddActivity.class) {
                    if (bean.getActivity().equals(CheckOnActivity.class)) {
                        // 从自己要参加的会议当中挑选一个进行签到
                        final String[] meetings = {"明后两天带薪休假", "下午5点开会", "一人说两句", "两人说四句", "......"};
                        DialogUtil.showItemsDialog(getActivity(), "选择签到的会议", meetings, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DialogUtil.showAlertDialog(getActivity(), "签到成功", "会议\"" + meetings[which] + "\"已经签到。");
                            }
                        });
                    } /*else if (bean.getActivity().equals(FilesInputActivity.class)) {
                        // 导入文件
                        Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                        intent2.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
                        startActivityForResult(intent2, 2);
                    } */ else {
                        startActivity(intent);
                    }

                } else {
                    Toast.makeText(getActivity(), "该功能暂未添加", Toast.LENGTH_SHORT).show();
                }
            } else {
                Bundle b = new Bundle();
                b.putString("yd", mSign);
                intent.putExtras(b);
                startActivityForResult(intent, ADD_ACTIVITY_REQUEST_CODE);
            }
        } else {
            Toast.makeText(getActivity(), "还没有登录！", Toast.LENGTH_SHORT).show();
            login();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ADD_ACTIVITY_REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    mSign = data.getExtras().getString("add");
                    if (!",".equals(data.getExtras().getString("addX"))) {
                        order += data.getExtras().getString("addX");
                    }
                    odr = AddFunctionUtils.getStrs(order, ",");
                    //获取资源
                    saveShare(mSign);
                    refresh();
                } else {
                }
                break;
            case LOGIN_REQUEST_CODE:
                // 从登录页面返回，并且登录成功，隐藏登录和注册的入口
                if (resultCode == SignInActivity.LOGIN_RESULT_CODE) {
                    setLoginState(true);
                }
                break;
            case 2:
                String selectedFilePath = data.getData().getPath();
                Toast.makeText(getActivity(), selectedFilePath, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 设置登录状态
     *
     * @param isLogin 是否已经登录
     */
    private void setLoginState(boolean isLogin) {
        mLoginRegister.setVisibility(isLogin ? View.GONE : View.VISIBLE);
        mLoginedHeader.setVisibility(isLogin ? View.VISIBLE : View.GONE);
        SmartCityApp.isLogin = isLogin;
        User user = new User();
        user.setObjectId(mUserInfo.get(SettingsUtil.KEY_PASSWORD));
        user.setUsername(mUserInfo.get(SettingsUtil.KEY_USERID));
        SmartCityApp.currentUser = isLogin ? user : null;
    }

    /**
     * 获取SharedPreferences保存的标记
     */
    public void getInitList() {
        String get = mPreferences.getString("ft_sign", "");
        order = mPreferences.getString("ft_order", "");
        int k = 0;
        String[] strs = new String[mAllList.size()];
        if (!("").equals(get)) {
            strs = AddFunctionUtils.getStrs(get, ",");
        } else {
            for (int i = 0; i < strs.length; i++) {
                strs[i] = "0";
                if (i == strs.length - 1) {
                    strs[i] = "1";
                }
            }
            //首次，默认几个功能
            strs[18] = "1";     // 预定会议
            strs[4] = "1";      // 会议签到
            strs[13] = "1";     // 资料导入
//            strs[14] = "1";     // 同步屏幕
//            strs[16] = "1";     // 手机投影
            strs[15] = "1";     // 呼叫服务
            strs[17] = "1";     // 投票表决
            strs[19] = "1";     // 会议进程
//            strs[20] = "1";     // 二维码名片
//            strs[0] = "1";    // 加班登记
//            strs[1] = "1";    // 出差申请
//            strs[5] = "1";    // 餐厅
//            strs[10] = "1";   // 联系客户
//            strs[11] = "1";     // 空调控制

//            order = "4,13,14,15,16,17,18";
//            order = "18,4,13,14,15,16,17,19,20";
            order = "18,4,13,15,17,19";
        }
        odr = AddFunctionUtils.getStrs(order, ",");
        mSign = AddFunctionUtils.getStr(strs, ",");
        refresh();
    }

    /**
     * 保存标记到SharedPreferences
     *
     * @param strings
     */
    public void saveShare(String strings) {
        mEditor = mPreferences.edit();
        mEditor.putString("ft_sign", strings);
        mEditor.putString("ft_order", order);
        mEditor.commit();

    }

    /**
     * 登录的REQUEST_CODE
     */
    public static final int LOGIN_REQUEST_CODE = 1010;
    private Intent mIntent;

    /**
     * 登录
     */
    private void login() {
        Intent intent = getIntentInstance(SignInActivity.class);
        startActivityForResult(intent, LOGIN_REQUEST_CODE);
//        TitleGrid
    }

    /**
     * @param target
     * @return
     */
    private Intent getIntentInstance(Class target) {
        if (mIntent == null) {
            mIntent = new Intent();
        }
        mIntent.setClass(getActivity(), target);
        return mIntent;
    }

    /**
     * 更新功能列表
     */
    public void refresh() {
        mListFuncations.clear();
        int len = odr.length;
        for (int i = 0; i < len; i++) {
            IndexFuncationListBean bean = mAllList.get(Integer.parseInt(odr[i]));
            bean.setIndex(i);
            mListFuncations.add(mAllList.get(Integer.parseInt(odr[i])));
        }
        // 添加功能的图标
//        mListFuncations.add(mAllList.get(mAllList.size() - 1));
//        for (int i = 0; i < len; i++) {
//            mListFuncations.get(i).setIndex(Integer.valueOf(odr[i]));
//        }
        mIndexFunctionAdapter = new IndexFunctionAdapter(getActivity(), this, mListFuncations);
        mGridView.setAdapter(mIndexFunctionAdapter);
        mIndexFunctionAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDelete(Object target, int position) {
        mHasDeleted = true;
//        int size = mListFuncations.size();
//        String[] orderString = new String[size];
//        for (int i = 0; i < size; i++) {
//            orderString[i] = String.valueOf(mListFuncations.get(i).getIndex());
//        }
//        order = AddFunctionUtils.getStr(orderString, ",");
//        // 修改SharedPreferences使得下次程序运行时首页模块变成此时的布局
//        saveShare(order);
    }

    class Click implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login:
                    login();
                    break;
                case R.id.register:
                    startActivity(getIntentInstance(CreateAccountAtivity.class));
                    break;
                case R.id.logined_avatar:
                    // 点击已经登录的头像，跳转到设置页面
//                    startActivity(getIntentInstance(SettingsActivity.class));
                    break;
            }
        }
    }

    /**
     * 移动之后的操作
     */
    private int o, n;

    public void moveItem() {
        Log.i("移动之前", order);
        if (!(o == mListFuncations.size() - 1 || n == mListFuncations.size() - 1)) {
            IndexFuncationListBean item = mListFuncations.get(o);
            mListFuncations.set(o, mListFuncations.get(n));
            mListFuncations.set(n, item);
            String move = odr[o];
            odr[o] = odr[n];
            odr[n] = move;
            order = AddFunctionUtils.getStr(odr, ",");
        }
        Log.i("移动之后", order);
        saveShare(mSign);
    }

    /**
     * gridview
     * item项移动后确定并返回
     */
    public boolean onBackPressed() {
        if (!mHasDeleted) {
            refresh();
        }
        if (mGridView.isEditMode()) {
            mGridView.stopEditMode();
            mIndexFunctionAdapter.setEditable(false);
        } else {
            return false;
        }
        return true;
    }

}
